package com.cc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.dto.DishDTO;
import com.cc.model.Dish;
import com.cc.mapper.DishMapper;
import com.cc.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Override
    public Dish create(DishDTO dishDTO) {
        Dish dish = new Dish();
        dish.setName(dishDTO.getName());
        dish.setCategoryId(dishDTO.getCategoryId());
        dish.setPrice(dishDTO.getPrice());
        dish.setDescription(dishDTO.getDescription());
        dish.setImageUrl(dishDTO.getImageUrl());
        dish.setStatus(dishDTO.getStatus());
        dish.setCreatedAt(LocalDateTime.now());
        dish.setUpdatedAt(LocalDateTime.now());
        dishMapper.insert(dish);
        return dish;
    }

    @Override
    public Dish update(Long id, DishDTO dishDTO) {
        Dish dish = dishMapper.selectById(id);
        if (dish != null) {
            dish.setName(dishDTO.getName());
            dish.setCategoryId(dishDTO.getCategoryId());
            dish.setPrice(dishDTO.getPrice());
            dish.setDescription(dishDTO.getDescription());
            dish.setImageUrl(dishDTO.getImageUrl());
            dish.setStatus(dishDTO.getStatus());
            dish.setUpdatedAt(LocalDateTime.now());
            dishMapper.updateById(dish);
        }
        return dish;
    }

    @Override
    public void delete(Long id) {
        dishMapper.deleteById(id);
    }

    @Override
    public Dish getByName(String name) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<Dish>()
                .eq(Dish::getName, name);
        return dishMapper.selectOne(queryWrapper);
    }

    @Override
    public Page<Dish> listByCategoryName(String categoryId, int page, int size) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<Dish>()
                .like(StringUtils.hasText(categoryId), Dish::getCategoryId, categoryId)
                .orderByAsc(Dish::getName);
        return dishMapper.selectPage(new Page<>(page, size), queryWrapper);
    }

    @Override
    public Page<Dish> list(int page, int size, String name) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<Dish>()
                .like(StringUtils.hasText(name), Dish::getName, name)
                .orderByAsc(Dish::getName);
        return dishMapper.selectPage(new Page<>(page, size), queryWrapper);
    }
} 